import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Like, Repository } from 'typeorm';
import BaseMaintainProject from '@main/entities/service/admin/base/base-maintain-project.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
import { generateExcelFn } from '@main/excel';
import { SysOperationLogService } from '../../system/operationLog/operationLog.service';

@Injectable()
export class BaseMaintainProjectService {
  constructor(
    @InjectRepository(BaseMaintainProject)
    private maintainProjectRepository: Repository<BaseMaintainProject>,
    private operationLogService: SysOperationLogService
  ) {}

  async list() {
    return await this.maintainProjectRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { maintainProjectName, maintainProjectCode, ids = [] } = entity;

    const where = {
      maintainProjectName: Like(`%${maintainProjectName}%`),
      maintainProjectCode: Like(`%${maintainProjectCode}%`),
    };

    if (ids && ids.length) {
      where['id'] = In(ids);
    }

    return await this.maintainProjectRepository.findAndCount({
      where,
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  async export(dto, lang) {
    const [list] = await this.page(dto);

    if (!list || !(list as any).length) {
      throw new ApiException(10052);
    }

    const dataList = list;

    return await generateExcelFn(
      {
        sheetName: 'machineMaintainProject',
        mainHeaderList: [
          {
            label: 'maintainProjectCode',
          },
          {
            label: 'maintainProjectName',
          },
          {
            label: 'remark',
          },
        ],
        dataList,
      },
      lang
    );
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const maintainProject = await this.maintainProjectRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'BaseMaintainProject',
      checkOnlyKeyList: [],
      data: maintainProject,
      whereObj: null,
      remark: `BaseMaintainProject表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `保养项目管理模块新增保养项目`,
        databaseOperationLogList,
        remark: `新增保养项目${data.maintainProjectName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const { id, maintainProjectName, remark } = data;

    await this.maintainProjectRepository.update(
      { id },
      { maintainProjectName, remark, updateName: user.nickName, updateUserName: user.userName }
    );
    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'BaseMaintainProject',
      checkOnlyKeyList: [],
      data: {
        maintainProjectName,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      },
      whereObj: { id },
      remark: `BaseMaintainProject表更新保养项目信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `保养项目管理模块更新保养项目信息`,
        databaseOperationLogList,
        remark: `更新保养项目${data.maintainProjectName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList: number[], user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    await this.maintainProjectRepository.delete(idList);
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'BaseMaintainProject',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `BaseMaintainProject表删除保养项目信息`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `保养项目管理模块删除保养项目`,
        databaseOperationLogList,
        remark: `删除保养项目`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  async isExistKey(data) {
    const { maintainProjectCode } = data;
    const result = await this.maintainProjectRepository.findOne({ where: { maintainProjectCode } });

    if (result) throw new ApiException(10048);
  }
}
